package com.kb.medical.service.impl;

import com.kb.medical.entity.UserFile;
import com.kb.medical.mapper.mp.EsMapper;
import com.kb.medical.mapper.mp.FileMapper;
import com.kb.medical.mapper.mp.PdfImageMapper;
import com.kb.medical.mapper.mp.PdfTxtMapper;
import com.kb.medical.service.FileService;
import com.kb.medical.service.es.EsService;
import com.kb.medical.service.ex.InsertException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.apache.tomcat.util.http.fileupload.FileUtils.deleteDirectory;

@Service
public class FileServiceImpl implements FileService {

    @Resource
    private FileMapper fileMapper;

    @Resource
    private PdfImageMapper pdfImageMapper;

    @Resource
    private PdfTxtMapper pdfTxtMapper;

    @Resource
    private EsMapper esMapper;


    @Resource
    private EsService esService;


    /**
     * 根据userid创建文件夹
     *
     * @param
     */
    @Override
    public String createFolder(int userid) {
        String folderName = "D:\\javacode\\medical\\src\\main\\resources\\uploadFile" + "/" + userid;
        System.out.println(folderName.toString());
        File folder = new File(folderName);
        // Check if folder exists and create it if it does not exist
        if (!folder.exists() && !folder.isDirectory()) {
            folder.mkdir();
        } else {
            System.out.println(userid + "Folder already exists");
        }
        return folderName.toString();
    }

    /**
     * 把文件信息插入数据库
     *
     * @param file 文件相关属性
     */
    @Override
    public void fileInsert(UserFile file) {
        String fileName = file.getFileName();
        UserFile result = fileMapper.findByFilename(fileName);
        if (result == null) {
            //抛出异常
            // 定义所需的日期时间格式
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
            String formattedDate = dateFormat.format(date);
            file.setUploadTime(formattedDate);
            //初始化点赞和点击数
            file.setLike(0);
            file.setClick(0);
            file.setScore(0);
            Integer rows = fileMapper.fileInsert(file);
            if (rows != 1) {
                throw new InsertException("在插入数据过程中产生了未知异常");
            }
        }

    }

    @Override
    public UserFile getByFileName(String fileName) {
        UserFile file = fileMapper.findByFilename(fileName);

        return file;
    }

    @Override
    public UserFile getById(int id) {
        UserFile userFile = fileMapper.findFileById(id);
        return userFile;
    }

    /**
     * 删除指定文件夹
     *
     * @param fileName 传入的路径
     * @return
     */
    @Override
    public void deleteFolder(String fileName) {
        File del_file = new File(fileName);
        try {
            deleteDirectory(del_file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 返回该用户所有的文件的所有相关信息
     *
     * @param userId 用户id
     * @param n      想要查询的页数
     * @return 返回该用户所有的文件的所有相关信息
     */
    @Override
    public List<UserFile> findByUserid(int userId, int n) {
        int m = 1000000;//显示八个对象
        n = (n - 1) * m; //分页显示公式
//        Pattern pattern = Pattern.compile("[^/]+/\\d+"); //正则表达式
        List<UserFile> list = fileMapper.findByUserid(userId, n, m);
        for (UserFile file : list) {
//            String path=pdfPath(file.getPdfPath());
//            file.setPdfPath("http:172.16.245.231:8080"+"/"+path+"/"+file.getFileName());//获取到的可下载pdf地址

        }
        return list;
    }

    /**
     * 获取pdfpath正则语句
     *
     * @param pdfPath
     * @return
     */
    @Override
    public String pdfPath(String pdfPath) {
//        String str = "D:\\javacode\\medical\\src\\main\\resources\\uploadFile/2";
        Pattern pattern = Pattern.compile("(?<=resources\\\\)(.*)");
        Matcher matcher = pattern.matcher(pdfPath);

        if (matcher.find()) {
            String result = matcher.group(1).replace("\\", "/");
//            uploadFile/2
//            System.out.println(result);
            return result;
        }
        return "";
    }

    @Override
    public void updatePage(int id, String path) {

        // 创建一个File对象来表示文件夹
        File folder = new File(path);

        // 使用listFiles()方法获取文件夹下的所有文件
        File[] files = folder.listFiles();
//        System.out.println("页数"+files.length);
        fileMapper.updatePage(files.length, id);

    }

    @Override
    public String localPath(String path) {
//        String str = "D:\\javacode\\medical\\src\\main\\resources\\uploadFile/41/影响人工关节置换术后下肢深静脉血栓形成的临床风险因素分析_关振鹏.pdf";
        Pattern pattern = Pattern.compile(".*\\\\uploadFile\\/(\\d+)\\/(.*)");
        Matcher matcher = pattern.matcher(path);
        if (matcher.matches()) {
            String url = "http://172.16.245.231:8080/uploadFile/" + matcher.group(1) + "/";
            String filename = matcher.group(2);
            return url + filename;
        }

        return null;
    }

    @Override
    public String pdfDownload(int documentId) {
        UserFile userFile = fileMapper.findFileById(documentId);
        Pattern pattern = Pattern.compile(".*\\/uploadFile\\/(\\d+)\\/(.*)");
        Matcher matcher = pattern.matcher(userFile.getPdfPath());
        if (matcher.matches()) {
            String filepath = "D:\\javacode\\medical\\src\\main\\resources\\uploadFile/" + matcher.group(1) + "/" + matcher.group(2);
            return filepath;
        }
        return null;
    }

    @Override
    public void updateClickByDocId(int click, int id) {
        fileMapper.updateClickByDocId(click, id);
        UserFile userFile = fileMapper.findFileById(id);
        int score = userFile.getScore();
//        pdfImageMapper.updateScore(score, id);
        pdfImageMapper.updateClick(userFile.getClick(), id);
//        pdfTxtMapper.updateScore(score, id);
        pdfTxtMapper.updateClick(userFile.getClick(), id);

        esService.updateClick(userFile.getClick(), id);
    }

    @Override
    public void updateLikeByDocId(int like, int id) {
        fileMapper.updateLikeByDocId(like, id);
        UserFile userFile = fileMapper.findFileById(id);
//        pdfImageMapper.updateScore(userFile.getScore(), id);
        pdfImageMapper.updateLike(userFile.getLike(), id);
//        pdfTxtMapper.updateScore(userFile.getScore(), id);
        pdfTxtMapper.updateLike(userFile.getLike(), id);

        esService.updateLike(userFile.getLike(), id);

    }

    @Override
    public String pdfRename(String pdfOldName) {
        int lastDotIndex = pdfOldName.lastIndexOf(".");
        if (lastDotIndex > 0) {
            String newFileName = pdfOldName.substring(0, lastDotIndex);
            return newFileName;
        }
        return null;
    }

    @Override
    public Integer deleteDataByDocumentId(int userId, int documentId) {
        if (fileMapper.findByDocId(userId, documentId) != null) {
            fileMapper.deleteImageByDocId(documentId);
            fileMapper.deletePdfTxtByDocId(documentId);
            fileMapper.deleteDocumentByDocId(documentId);
            esService.deleteEsDataByDocumentId(userId, documentId);
            return 1;
        } else {
            return 0;
        }

    }


}


